package com.test.ipc.socket;

import com.test.ipc.Logger;

import java.io.*;
import java.net.Socket;

public class Child {
    private static final String TAG = "Socket.Child";
    private static DataOutputStream mDataOutputStream = null;
    private static DataInputStream mDataInputStream = null;
    private static Socket mClientSocket = null;
    private static int mPort = 9923;

    public static void main(String[] args) {

        for (int i=0; i<args.length; i++) {
            switch (args[i]) {
                case "-p":
                    mPort = Integer.parseInt(args[i+1]);
                    i++;
                    break;
                default:
                    break;
            }
        }
        Logger.d(TAG+",服务端的端口号：" + mPort);

        try {
            mClientSocket = new Socket("127.0.0.1", mPort);
            Logger.d(TAG+",客户端的端口号："+ mClientSocket.getLocalPort());
            mDataInputStream = new DataInputStream(mClientSocket.getInputStream());
            mDataOutputStream = new DataOutputStream(mClientSocket.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            Logger.e(TAG + "," + e.getMessage());
        }

        Thread mReadThread = new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader bfr = new BufferedReader(new InputStreamReader(mDataInputStream));
                while (true) {
                    try {
                        String strLine = bfr.readLine();
                        if (strLine != null) {
                            Logger.d(TAG+",Rcv: "+strLine);
                            String str = "hi:" + strLine + "\n\r";
                            mDataOutputStream.write(str.getBytes("UTF-8"));
                            mDataOutputStream.flush();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Logger.e(TAG+","+e.getMessage());
                        break;
                    }
                }
            }
        });
        mReadThread.start();

        try {
            mReadThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            mDataInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mDataOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            mClientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
